<template>
  <el-dropdown>
    <span class="el-dropdown-link">
      <el-avatar shape="square" :size="40" :src="squareUrl" />
      &nbsp;&nbsp;{{ userInfo.username }}
      <el-icon class="el-icon--right">
        <arrow-down />
      </el-icon>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item
          ><router-link :to="{ name: '个人中心' }"
            >个人中心</router-link
          ></el-dropdown-item
        >
        <el-dropdown-item v-if="!userInfo" @click="goLogin"
          >去登录</el-dropdown-item
        >
        <el-dropdown-item v-else @click="logoutFun">安全退出</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>
<script setup>
import { ArrowDown } from "@element-plus/icons-vue";
import { computed, watch, ref } from "vue";
import router from "@/router";
import { getUserAvatar, logout } from "@/api/user";
import store from "@/store";
import Cookies from "js-cookie";
const userInfo = computed(() => store.state.userInfo);
console.log("userInfo", userInfo);
// const squareUrl = ref(
//   "http://127.0.0.1:8000/media/userAvatar/" + userInfo?.value.avatar
// );
const squareUrl = ref(
  userInfo?.value.avatar
    ? "http://127.0.0.1:8000/media/userAvatar/" + userInfo?.value.avatar
    : ""
);
console.log("squareUrl", squareUrl);
watch(
  () => userInfo.value,
  (newAvatar) => {
    console.log("newAvatar", newAvatar);
    squareUrl.value =
      "http://127.0.0.1:8000/media/userAvatar/" + newAvatar.userInfo.avatar;
  }
);
// watch(userInfo, (newUserInfo) => {
//   console.log("newUserInfo", newUserInfo,userInfo);
//   if (newUserInfo?.value?.avatar) {
//     squareUrl =
//       "http://127.0.0.1:8000/media/userAvatar/" + newUserInfo.userInfo[0].avatar;
//   } else {
//     squareUrl = "http://127.0.0.1:8000/media/userAvatar/defaultAvatar.png"; // 设置默认头像
//   }
// });

const goLogin = () => {
  router.replace("/login");
};
const logoutFun = async () => {
  localStorage.clear();
  store.commit("RESET_TABS");
  store.commit("RESET_MENU");
  sessionStorage.removeItem("menuList");
  sessionStorage.removeItem("userInfo");
  localStorage.removeItem("userId");
  // Cookies.remove("sessionid");
  let result = await logout();
  console.log("result", result);
  router.replace("/login");
};
</script>
<style lang="scss" scoped>
.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>
